package com.example.Hongbao;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

public class MyWindowManager {

	/**
	 * 悬浮窗View的实例
	 */
	private static View windowView;

	/**
	 * 悬浮窗View的参数
	 */
	private static LayoutParams windowParams;

	/**
	 * 用于控制在屏幕上添加或移除悬浮窗
	 */
	private static WindowManager mWindowManager;

	/**
	 * 创建一个悬浮窗。位置为屏幕正中间。
	 *
	 * @param context 必须为应用程序的Context.
	 */
	public static void createWindow(Context context) {
		WindowManager windowManager = getWindowManager(context);
		int screenWidth = windowManager.getDefaultDisplay().getWidth();
		int screenHeight = windowManager.getDefaultDisplay().getHeight();
		if (windowView == null) {
			windowView = LayoutInflater.from(context).inflate(R.layout.anim, null);
			if (windowParams == null) {
				windowParams = new LayoutParams();
				// 类型
//				windowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
				windowParams.type = LayoutParams.TYPE_PHONE;
				windowParams.alpha = 0.8f;
				windowParams.format = PixelFormat.RGBA_8888;
				windowParams.gravity = Gravity.CENTER;
				windowParams.width = (int) (screenWidth * 0.8);
				windowParams.height = (int) (screenHeight * 0.8);
				//强制竖屏
				windowParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
				windowParams.flags = LayoutParams.FLAG_ALT_FOCUSABLE_IM
					| LayoutParams.FLAG_NOT_FOCUSABLE;
				;
				// 不设置这个弹出框的透明遮罩显示为黑色
				windowParams.format = PixelFormat.TRANSPARENT;
			}
			windowManager.addView(windowView, windowParams);
		}
	}

	/**
	 * 将浮窗从屏幕上移除。
	 *
	 * @param context 必须为应用程序的Context.
	 */
	public static void removeWindow(Context context) {
		if (windowView != null) {
			WindowManager windowManager = getWindowManager(context);
			windowManager.removeView(windowView);
			windowView = null;
		}
	}

	/**
	 * 是否有悬浮窗显示在屏幕上。
	 *
	 * @return 有悬浮窗显示在桌面上返回true，没有的话返回false。
	 */
	public static boolean isWindowShowing() {
		return windowView != null;
	}

	/**
	 * 如果WindowManager还未创建，则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。
	 *
	 * @param context 必须为应用程序的Context.
	 * @return WindowManager的实例，用于控制在屏幕上添加或移除悬浮窗。
	 */
	private static WindowManager getWindowManager(Context context) {
		if (mWindowManager == null) {
			mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		}
		return mWindowManager;
	}
}
